<template>
  <el-dialog
    title="回退"
    :visible="visible"
    class="dialog-class1 dialogStyle"
    width="560px"
    @open="getBackLink"
    @close="resetForm"
    :destroy-on-close="true"
  >
    <el-form
      ref="form"
      :model="ruleForm"
      :rules="rules"
      label-width="90px"
      v-loading="loading"
    >
      <el-form-item label="回退环节" prop="rollbackLink">
        <el-select
          v-model="ruleForm.rollbackLink"
          @change="getUserTree"
          placeholder="请选择"
        >
          <el-option
            v-for="item in selectDatas.rollbackLinkList"
            :key="item.value"
            :label="item.linkName"
            :value="item.linkId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        class="rollback-select select-user"
        label="处理人"
        prop="userList"
      >
        <tree-select
          v-model="ruleForm.userList"
          :allUserTreeData="allUserTreeData"
          :userTreeData="userTreeData"
          :lastProcess="lastProcess"
          node-key="id"
          default-expand-all
          show-checkbox
          ref="treeSelect"
          :config="{ label: 'userName', value: 'userId' }"
          @check-change="handleCheckChange"
          :isShowAllBtn="isShowAllBtn"
          :isShowAllInfo.sync="isShowAllInfo"
          :nextLinkInfo="
            this.selectDatas.rollbackLinkList.find(
              (item) => item.curLink == this.ruleForm.rollbackLink
            )
          "
        />
      </el-form-item>
      <div class="position-info">
        <editUsefulWord
          :isShowUsefulWord.sync="isShowUsefulWord"
        ></editUsefulWord>
      </div>
      <el-form-item label="回退说明" class="small tip" prop="desc">
        <el-input
          type="textarea"
          v-model="ruleForm.desc"
          placeholder="请输入"
          resize="none"
          size="small"
          maxlength="200"
        ></el-input>
      </el-form-item>
      <el-form-item v-show="isShowUsefulWord">
        <useful-word
          style="margin-top: -19px"
          :desc.sync="ruleForm.desc"
          :isShowUsefulWord.sync="isShowUsefulWord"
        ></useful-word>
      </el-form-item>
      <el-form-item>
        <FormItemIconTipLabel slot="label" />
        <EventFileUpload
          v-model="ruleForm.orderFileDTOList"
          :loading.sync="uploading"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        @click="submitForm"
        :loading="btnLoading || uploading"
        style="margin-right: 9px"
        >确 定</el-button
      >
      <el-button @click="resetForm">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getUserTree,
  queryRollbackLink,
  queryLastProcess,
} from "@/api/modules/eventManagement/eventDispatch.js";
import { rollBack } from "@/api/modules/eventManagement/eventCheck.js";
import TreeSelect from "@/components/TreeSelect";
import { $getUrlParam } from "@/utils/public";
import UsefulWord from "@/views/pages/eventManagement/eventDialog/usefulWord";
import editUsefulWord from "@/views/pages/eventManagement/eventDialog/editUsefulWord";
import EventFileUpload from "../components/EventFileUpload";
import FormItemIconTipLabel from "../components/FormItemIconTipLabel";
export default {
  name: "rollbackDialog",
  components: {
    TreeSelect,
    UsefulWord,
    editUsefulWord,
    EventFileUpload,
    FormItemIconTipLabel,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    orderData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      ruleForm: {
        rollbackLink: "",
        userList: "",
        desc: "",
      },
      userTreeData: [],
      loading: false,
      selectDatas: {
        rollbackLinkList: [],
        nameList: [],
      },
      rules: {
        rollbackLink: [
          {
            required: true,
            message: "请选择回退环节",
            trigger: ["blur", "change"],
          },
        ],
        userList: [
          {
            required: true,
            message: "请选择人员",
            trigger: ["blur", "change"],
          },
        ],
        desc: [
          {
            validator: (rule, value, callback) => {
              if (value.length >= 200) {
                callback("字数请控制在200字符以内");
              } else callback();
            },
            trigger: ["blur", "change"],
          },
        ],
      },
      isTenantAdmin: this.$store.getters.userInfo.isTenantAdmin, // 1 租户管理员
      lastProcess: "",
      allUserTreeData: [],
      isShowAllBtn: true /** 是否显示全部处理人按钮 */,
      isShowAllInfo: false, // 是否显示全部处理人
      isShowUsefulWord: false, // 是否显示常用语列表
      btnLoading: false,
      uploading: false,
    };
  },
  methods: {
    resetForm() {
      this.$emit("update:visible", false);
      this.ruleForm = {
        rollbackLink: "",
        userList: "",
        desc: "",
      };
      this.userTreeData = [];
      this.isShowAllBtn = false; /** 是否显示全部处理人按钮 */
      this.isShowAllInfo = false; // 是否显示全部处理人
      this.isShowUsefulWord = false; // 是否显示常用语列表
    },
    async getBackLink() {
      this.btnLoading = false;
      this.loading = false;
      const res = await queryRollbackLink({
        orderId: this.orderData.warningOrderId,
        linkId: this.orderData.linkId,
      });
      if (res.code === 200) {
        // debugger
        this.selectDatas.rollbackLinkList = res.data;
        if (
          this.selectDatas.rollbackLinkList &&
          this.selectDatas.rollbackLinkList.length == 1
        ) {
          this.ruleForm.rollbackLink =
            this.selectDatas.rollbackLinkList[0].linkId;
          await this.getUserTree(this.ruleForm.rollbackLink);
        }
      }
    },
    handleCheckChange(data, checked, indeterminate) {
      // const nodes = this.$refs.tree.getCheckedNodes();
      // this.ruleForm.userList = nodes?.filter((elem) => elem.userList);
      // console.log(JSON.parse(JSON.stringify(data)), nodes, "00");
    },
    // 字段转换
    transferTreeData(list) {
      return list.map((node) => {
        const { nodeId, ...rest } = node;
        let nodeName = node.userName || node.nodeName;
        const obj = {
          id: nodeId,
          label: nodeName,
          ...rest,
        };
        if (node.children) {
          return {
            ...obj,
            children: this.transferTreeData(node.children),
          };
        }
        return obj;
      });
    },
    async getUserTree(linkParam) {
      const selectLinkData = this.selectDatas.rollbackLinkList.filter(
        (item) => item.linkId === linkParam
      );
      this.isShowAllBtn = !(
        selectLinkData[0].dataFilterPermiss === "0" &&
        selectLinkData[0].customAdmin === "1"
      );
      this.isShowAllInfo =
        selectLinkData[0].dataFilterPermiss === "0" && !this.isShowAllBtn;
      let lastProcess = await queryLastProcess({
        orderId: this.orderData.warningOrderId,
        linkId: this.ruleForm.rollbackLink,
      });
      if (lastProcess.code == 200) {
        this.lastProcess = lastProcess.data.processId;
      }
      this.userTreeData = [];
      const params = {
        curLink: linkParam,
        tenantId: this.$store.getters.userInfo.tenantId
          ? this.$store.getters.userInfo.tenantId
          : this.orderData.tenantId,
        flowId: this.orderData.flowId,
        deviceCode: this.orderData.deviceCode,
        provinceId: this.orderData.provinceId,
        cityId: this.orderData.cityId,
        countyId: this.orderData.countyId,
        warningSource: this.orderData.warningSource,
        gridId: this.orderData.gridId,
        warningTypeId: this.orderData.warningTypeId,
      };
      this.loading = true;
      getUserTree(params).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.userTreeData = this.transferTreeData([res.data.sysPowerInfo]);
          this.allUserTreeData = this.transferTreeData([res.data.sysAllInfo]);
          this.userTreeData[0].root = 1;
          this.allUserTreeData[0].root = 1;
          this.$nextTick(() => {
            this.$refs.treeSelect.checkTreeChange();
          });
        }
      });

      // this.dataList = [];
      // this.generateList(this.userTreeData);
    },
    refreshSelectedTag(view, realLinkType) {
      location.reload();
    },
    async submitForm() {
      const valid = await this.$refs.form.validate();
      if (!valid) {
        return;
      }

      if (!this.ruleForm.userList || this.ruleForm.userList.length === 0) {
        return;
      }
      let _this = this;
      let flowDataInfo = {};
      for (let i = 0; i < _this.selectDatas.rollbackLinkList.length; i++) {
        let row = _this.selectDatas.rollbackLinkList[i];
        if (row.linkId == _this.ruleForm.rollbackLink) {
          flowDataInfo = row;
          break;
        }
      }
      flowDataInfo.nextEnableAcceptanceMode = flowDataInfo.enableAcceptanceMode;
      flowDataInfo.enableAcceptanceMode = this.orderData.enableAcceptanceMode;
      let params = {
        ...flowDataInfo,
        flowId: _this.flowId,
        flowTemplate: _this.flowTemplate,
        orderId: _this.orderData.warningOrderId,
        warningOrderId: _this.orderData.warningOrderId,
        currentOrderStatus: this.orderData.orderStatus, //4-处置；5-核实
        backType: _this.ruleForm.rollbackLink, //0-回退到调度 1-回退到处置
        remark: _this.ruleForm.desc,
        orderApproveVOList: [
          {
            approveResult: _this.ruleForm.desc,
          },
        ],
        enableAcceptanceMode: this.orderData.enableAcceptanceMode, // 当前事件受理状态（0：不开启 1：开启（待受理）2：已受理 3：受理完成）
        devicePitch: this.orderData.devicePitch, // 俯仰角
        alarmReason: this.orderData.alarmReason, // 告警原因
        deviceHorizontal: this.orderData.deviceHorizontal, // 水平角
      };
      // 附件
      if (this.orderData.orderStatus == 4) {
        params.processOrderVOList = [
          { processImgList: this.ruleForm.orderFileDTOList },
        ];
      } else {
        params.orderFileDTOList = this.ruleForm.orderFileDTOList;
      }
      if (this.orderData.updateAddress) {
        params.address = this.orderData.address;
        params.longitude = this.orderData.longitude;
        params.latitude = this.orderData.latitude;
        params.gridId = this.orderData.gridId;
        params.gridName = this.orderData.gridName;
        params.horiAzimuthAngle = this.orderData.horiAzimuthAngle;
        params.checkGridFlag = "1"; // 是否修改网格员  1 是  0 否
      } else {
        params.checkGridFlag = "0";
      }
      params.warningTypeId = this.orderData.warningTypeId;
      params.processDTOList = this.ruleForm.userList.map((ele) => ({
        processId: ele.userId,
        processName: ele.userName,
        groupId: "",
      }));
      params.realLinkType = this.selectDatas.rollbackLinkList.filter(
        (item) => item.linkId == this.ruleForm.rollbackLink
      )[0].realLinkType;
      params.flowLinkType = "2";
      params.cityId = this.orderData.cityId;
      params.countyId = this.orderData.countyId;
      params.provinceId = this.orderData.provinceId;
      if (this.selectDatas.rollbackLinkList.length === 1) {
        params.backType = this.ruleForm.rollbackLink.linkId;
      }
      this.btnLoading = true;
      rollBack(params).then((resp) => {
        this.btnLoading = false;
        let msgId = {
          id: this.orderData.warningOrderId,
          status: this.orderData.orderStatus,
        };
        this.$store.dispatch("closeSocketMsg", msgId);
        if (resp && resp.code == 200) {
          let userId = this.$store.getters.userInfo.userId;
          if (
            (Array.isArray(this.ruleForm.userList) &&
              this.ruleForm.userList.find((item) => item.userId == userId)) ||
            this.isTenantAdmin == "1"
          ) {
            // 有下一环节处理权限就自动打开下一环节
            this.$store.dispatch("tagsView/delView", this.$route);
            this.refreshSelectedTag(this.$route, params.realLinkType);
            $message.success("回退成功");
          } else {
            this.onSuccess();
          }
          this.resetForm();
        } else {
          $message.error(resp.msg);
        }
      });
      // console.log(this.$route.fullPath,"路由信息");
      // // 刷新当前路由**需要修改orderStatus
      // this.refreshSelectedTag(this.$route)
    },
    onSuccess() {
      const url =
        $getUrlParam("pageType") === "false"
          ? "/eventManagement"
          : "/eventManagement/myEvent";
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push(url);
    },
    replaceParamVal(oUrl, paramName, replaceWith) {
      var re = eval("/(" + paramName + "=)([^&]*)/gi");
      var nUrl = oUrl.replace(re, paramName + "=" + replaceWith);
      return nUrl;
    },
  },
};
</script>

<style scoped lang="scss">
/deep/.el-dialog > .el-dialog__body {
  padding: 20px 60px 0;
}
/deep/ .el-form-item__error {
  position: relative;
}
/deep/.select-user .el-form-item__error {
  position: absolute;
  top: 35px;
  left: 5px;
}

/deep/.tip .el-form-item__error {
  padding-left: 5px;
}
.position-info {
  margin-top: -10px;
  padding-right: 5px;
  margin-bottom: 5px;
}
/deep/ .el-select__tags {
  overflow: auto;
  .el-tag.el-tag--info {
    max-width: 80%;
  }
}
/deep/.rollback-select .el-select__tags-text {
  overflow: hidden;
  text-overflow: ellipsis;
}

.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 4px;
  }
  /deep/ .el-dialog__header {
    padding: 12px;
  }
  /deep/ .el-dialog__footer {
    padding: 12px;
  }
  /deep/ .el-form-item--small.el-form-item {
    margin-bottom: 12px;
  }
  /deep/ .el-form-item .el-form-item__label {
    padding-right: 9px;
  }
  /deep/ .el-textarea__inner {
    height: 60px;
  }
}
</style>
